<template>
  <!-- 登录页 -->
  <div class="login-container">
    <div class="form-background">
      <div class="title-container">
        <el-image class="logo" :src="logo" fit="fill" />
        <p class="title">工程监管系统</p>
      </div>
      <div class="login-form">
        <div class="pass-title">
          <div v-if="passShow" class="pass-title-info" @click="passClick()">
            <img class="text" :src="codeText" alt>
            <img class="pic" :src="code" alt>
          </div>
          <div v-else class="pass-title-info" @click="passClick()">
            <img class="text" :src="pass" alt>
            <img class="pic" :src="web" alt>
          </div>
        </div>
        <el-form v-if="passShow" ref="loginForm" :model="loginForm" :rules="loginRules" label-width="0px" autocomplete="on" label-position="left">

          <el-form-item prop="username">
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="账号"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
              @input="changeUserName"
            >
              <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>

          <el-tooltip :value="capsTooltip" content="大写模式已开启" placement="right" manual>
            <el-form-item prop="password">
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="密码（由数字加字母且大于6位）"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              >
                <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
              </el-input>
              <span class="show-pwd" @click="showPwd">
                <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </el-form-item>
          </el-tooltip>

          <el-form-item prop="code">
            <el-input
              v-model="loginForm.code"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
              <i slot="suffix" class="el-icon-refresh" style="cursor:pointer;" @click="getCode" />
            </el-input>
            <div class="login-code">
              <img v-if="showCode" :src="codeUrl" @click="getCode">
              <svg-icon v-if="!showCode" icon-class="pic-broken" style="cursor:pointer;width: 100px;height: 40px;" @click="getCode" />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button v-if="!loading" type="primary" class="submit" @click.native.prevent="handleLogin">
              <span>登 录</span>
            </el-button>
            <el-button v-else type="primary" class="submit">
              <span>登 录 中...</span>
            </el-button>
            <p class="go-register">
              <span @click="toEnterprise">企业注册</span>
              <span @click="toPersonal">个人注册</span>
              <span @click="toForgetPassword">忘记密码？</span>
            </p>
          </el-form-item>

        </el-form>
        <div v-else class="code">
          <div class="scan-code">
            <div v-show="isMark" class="mark">
              <i class="el-icon-refresh-right" :class="{'icon-animate':isAnimate}" @click="resetLoad" />
            </div>
            <vue-qr
              class="qr-code"
              :size="100"
              :margin="0"
              :auto-color="true"
              :dot-scale="1"
              :text="loginUrl"
            />
          </div>
        </div>
      </div>
      <!-- 选择角色-->
      <div />
    </div>
  </div>
</template>

<script>
import vueQr from 'vue-qr'
import { getWxLoginUrl, checkLogin } from '@/api/common/login'
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { validUsername } from '@/utils/validate'
import { getEnterpriseType } from '@/utils/auth'
import Cookies from 'js-cookie'
import logo from '@/assets/image/logo.png'
import codeText from '@/assets/image/code-text.png'
import code from '@/assets/image/code.png'
import pass from '@/assets/image/pass.png'
import web from '@/assets/image/web.png'
// 验证码接口
import { captchaImage } from '@/api/user'
import { validateNumLetter } from '@/utils/validate.js'
// import wxlogin from 'vue-wxlogin'
export default {
  name: 'Login',
  components: {
    // wxlogin,
    vueQr
  },
  data() {
    // 验证用户名
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else if (value.length < 2) {
        callback(new Error('用户名长度不能小于2'))
      } else if (value.length > 20) {
        callback(new Error('用户名长度不能20位'))
      } else {
        callback()
      }
    }
    // 验证密码
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6 || value.length > 20) {
        return callback(new Error('登录密码不能少于6位且不能大于20位'))
      } else {
        callback()
      }
    }
    return {
      isAnimate: false,
      isMark: false,
      // 检测登录定时器
      timer: null,
      // 检测次数
      count: 0,
      loginUrl: '',
      title: '账号登录',
      passShow: true,
      logo: logo, // logo图片地址
      codeText: codeText,
      code: code,
      pass: pass,
      web: web,
      showCode: false, // 验证码正常显示
      codeUrl: '', // 验证码
      loginForm: { // 登录表单
        username: '',
        password: '',
        code: '',
        uuid: ''
      },
      loginRules: { // 登录表单验证
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword },
          { required: true, validator: validateNumLetter }
        ],
        code: [{ required: true, trigger: 'blur', message: '验证码不能为空' }]
      },
      passwordType: 'password', // 密码图标
      capsTooltip: false, // 判断是否开启大写模式
      loading: false,
      redirect: undefined // 指定路径
    }
  },
  watch: {
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  created() {
    // 图片验证
    this.getCode()
    // 获取cookie
    this.getCookie()
  },
  mounted() {
    // 用户名和密码自动获取光标
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  methods: {
    // 重置加载二维码
    resetLoad() {
      this.isAnimate = true
      this.getwxCode()
    },
    // 切换二维码
    passClick() {
      this.passShow = !this.passShow
      if (!this.passShow) {
        this.$nextTick(() => {
          this.hideIframeTitle()
        })
        this.scan-code()
      } else {
        clearInterval(this.timer)
      }
    },
    // 获取微信登录二维码
    async getwxCode() {
      const url = await getWxLoginUrl()
      if (url) {
        this.isAnimate = false
        this.isMark = false
        // 解析时间戳
        this.loginUrl = url
        const index = url.indexOf('?')
        const query = url.substr(index)
        const time = query.split('=')[1]
        this.timer = setInterval(async() => {
          // 每2秒检测一次是否扫码
          const { data } = await checkLogin(time)
          this.count += 1
          // 请求超出30次
          if (this.count >= 5) {
            this.count = 0
            clearInterval(this.timer)
            this.isMark = true
            return
          }
          if (data) {
            clearInterval(this.timer)
            this.$store.dispatch('user/scanCodeLogin', data).then(res => {
              this.goIndex(res)
            })
          }
        }, 2000)
      }
    },
    hideIframeTitle() {
      // const Title = this.$refs.wxlogin.contentWindow.document.getElementsByClassName('.title')
      // const img = this.$refs.wxlogin.contentWindow.document.getElementsByName('img')
      // Title.style.display = 'none'
      // img.style.display = 'none'
    },
    // 改变用户名清空密码
    changeUserName(e) {
      if (e) {
        this.loginForm.password = ''
      }
    },
    // 图片验证
    getCode() {
      captchaImage().then(res => {
        this.codeUrl = 'data:image/gif;base64,' + res.data.img
        this.loginForm.uuid = res.data.uuid
        this.showCode = true
      }).catch(() => {
        this.showCode = false
      })
    },
    // cookie 存放
    getCookie() {
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      this.loginForm.username = username === undefined ? this.loginForm.username : username
      this.loginForm.password = password === undefined ? this.loginForm.password : decrypt(password)
    },
    // 判断是否开启大写模式
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (shiftKey && (key >= 'a' && key <= 'z') || !shiftKey && (key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    // 是否显示密码
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 登录
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then((res) => {
              this.goIndex(res.data)
            })
            .catch((res) => {
              this.loading = false
              // 重新刷新图片
              this.getCode()
            })
        } else {
          return false
        }
      })
    },
    goIndex(data) {
      if (data.login_type !== '1') {
        this.$store.dispatch('user/getInfo').then((res) => {
          this.$store.dispatch('basicInfo/getDicts') // 个人字典
          this.$store.dispatch('basicInfo/getSysDicts') // 系统字典
          const EnterpriseType = getEnterpriseType()
          switch (EnterpriseType) {
            case '1': // 监管单位
              this.$router.push({ path: '/' })
              break
            case '2': // 勘察企业
              this.$router.push({ path: '/enterpriseIndex' })
              break
            case '3': // 供应商
              this.$router.push({ path: '/supplierIndex' })
              break
            default:
              this.$router.push({ path: this.redirect || '/enterpriseIndex' })
          }
        })
      } else {
        this.$router.push({ path: this.redirect || '/' })
      }
    },
    // 跳转企业注册
    toEnterprise() {
      this.$router.push({
        path: '/EnterpriseRegister'
      })
    },
    // 跳转企业注册
    toPersonal() {
      this.$router.push({
        path: '/register'
      })
    },
    // 跳转转会密码
    toForgetPassword() {
      this.$router.push({
        path: '/forget-password'
      })
    }
  }
}
</script>

<style lang="scss">
.scan-code {
  width: 200px;
  height: 200px;
  margin: 20px auto;
  position: relative;
  padding: 10px;
  border: 1px solid #999;
  .mark {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: #000;
    text-align: center;
    opacity: .8;
    i {
      font-size: 50px;
      line-height: 200px;
      cursor: pointer;
      color: #fff;
    }
    .icon-animate {
      animation: demo .3s linear infinite;
    }
  }
  .qr-code {
    height: 100%;
  }
}

@keyframes demo {
  0% {
    transform: rotate(0deg);
  }

  100% {
     transform: rotate(360deg);
  }
}

</style>

